package 剑指offer;


import java.util.ArrayList;

/**
 * Created by root on 17-3-1.
 * {1,2,3,4,5,3,5,#,2,#}
 */
public class CopyComplexLinked {
    ArrayList<Integer> randomIndex = new ArrayList<>();
    ArrayList<RandomListNode> randomListNodes = new ArrayList<>();
    public RandomListNode Clone(RandomListNode pHead)
    {
        if (pHead == null) {
            return null;
        }
        RandomListNode temp1 = pHead;
        RandomListNode temp2 = pHead;
        traverseRandomListNode(temp1);
        setRandomListNode(temp2);
        RandomListNode temp3 = randomListNodes.get(0);
        while(temp3.next != null) {
            System.out.println(temp3.label + "----"+temp3.random.label);
            temp3 = temp3.next;
        }
        return randomListNodes.get(0);
    }

    public void traverseRandomListNode(RandomListNode pHead) {

        if (pHead == null) {
            return;
        }
        RandomListNode tmp = new RandomListNode(pHead.label);
        if(!randomListNodes.isEmpty()) {
            randomListNodes.get(randomIndex.size() - 1).next = tmp;
        }
        randomIndex.add(pHead.label);
        randomListNodes.add(tmp);
        traverseRandomListNode(pHead.next);
    }

    public void setRandomListNode(RandomListNode pHead) {

        if (pHead == null) {
            return;
        }
        // find index
        int next = 0;
        while (pHead.next != null) {
            if (pHead.random == null) {
                next ++;
                pHead = pHead.next;
                continue;
            }
            int index = randomIndex.indexOf(pHead.random.label);
            randomListNodes.get(next).random = randomListNodes.get(index);
            next ++;
            pHead = pHead.next;
        }
    }
}
